package com.xuhuan.client.util;

import com.xuhuan.client.business.splitfile.dto.ZoneInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StopWatch;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author huan.xu
 * @Date 2023/6/16 22:29
 * @Description 文件处理工具类
 */
@Slf4j
public class FileHandleUtil {

    private FileHandleUtil() {
    }

    /**
     * 根据文件名获取文件前缀名
     *
     * @param fileName
     * @return
     */
    public static String getFilePrefixName(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return "";
        }
        int index = fileName.lastIndexOf(".");
        if (index == -1) {
            return "";
        }
        return fileName.substring(0, index);
    }

    /**
     * 根据文件名获取文件后缀名
     *
     * @param fileName
     * @return
     */
    public static String getFileExName(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return "";
        }
        int index = fileName.lastIndexOf(".");
        if (index == -1) {
            return "";
        }
        return fileName.substring(index + 1);
    }

    /**
     * 获取文件md5值
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public static String md5HashCode(String filePath) throws Exception {
        return md5HashCode(new File(filePath));
    }

    /**
     * 获取文件md5值
     *
     * @param file 文件
     * @return
     * @throws Exception
     */
    public static String md5HashCode(File file) throws Exception {
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        InputStream fis = new FileInputStream(file);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int length = -1;
        while ((length = fis.read(buffer, 0, 1024)) != -1) {
            md.update(buffer, 0, length);
        }
        fis.close();

        //转换并返回包含16个元素字节数组,返回数值范围为-128到127
        byte[] md5Bytes = md.digest();
        BigInteger bigInt = new BigInteger(1, md5Bytes);
        String md5HashCode = bigInt.toString(16);
        return md5HashCode;
    }

    /**
     * 计算目录下文件的md5值
     *
     * @param dir
     * @return
     */
    public static List<ZoneInfo> handleDirMd5(File dir) {
        List<ZoneInfo> zoneInfoList = new ArrayList<>();
        Arrays.stream(dir.listFiles())
                .filter(file -> file.isFile())
                .forEach(file -> {
                    try {
                        ZoneInfo zoneInfo = new ZoneInfo();
                        String md5HashCode = md5HashCode(file);
                        zoneInfo.setZoneMd5(md5HashCode);
                        zoneInfo.setPath(file.getPath());
                        zoneInfo.setName(file.getName());
                        zoneInfoList.add(zoneInfo);
                    } catch (Exception e) {
                        log.error(ExceptionUtils.getFullStackTrace(e));
                        throw new RuntimeException("计算分片md5失败");
                    }
                });
        return zoneInfoList;
    }


    /**
     * 求一个字符串的md5值
     * @param target 字符串
     * @return md5 value
     */
    public static String MD5(String target) {
        return DigestUtils.md5Hex(target);
    }

    /**
     * 对list进行排序，然后计算md5值
     * @param list
     * @return
     */
    public static String md5List(List<String> list){
        if(CollectionUtils.isEmpty(list)){
            return "";
        }
        String target = list.stream().sorted().collect(Collectors.joining(","));
        return MD5(target);
    }


    public static void main(String[] args) throws Exception {
        System.out.println(MD5("1234qwer"));
    }



}
